import { ICtrlMsgModel } from "@/core/interface";

/**
 * 界面引擎容器
 *
 * @export
 * @class CtrlMsgContainer
 */
export class CtrlMsgContainer {

    /**
     * 部件消息Map
     *
     * @private
     * @type {Map<string, ICtrlMsgModel>}
     * @memberof CtrlMsgContainer
     */
    private CtrlMsgMap: Map<string, ICtrlMsgModel> = new Map();

    /**
     * Creates an instance of CtrlMsgContainer.
     * @param {ICtrlMsgModel[]} model
     * @memberof CtrlMsgContainer
     */
    public constructor(model: ICtrlMsgModel[]) {
        this.init(model);
    }


    /**
     *
     *
     * @param {ICtrlMsgModel[]} model
     * @memberof CtrlMsgContainer
     */
    public init(model: ICtrlMsgModel[]) {
        for (let index = 0; index < model.length; index++) {
            const item = model[index];
            this.CtrlMsgMap.set(item.name, item);
        }
    }


    /**
     * 
     *
     * @memberof CtrlMsgContainer
     */
    public formatMsgContent(msgModel: ICtrlMsgModel, param: { context: any, viewParams: any, data: any }): string {
        let { content } = msgModel;
        var reg = /[^\{\}]+(?=\})/g;
        // 获取字符串中 被${} 包起来的元素
        const dynaMsg = content.match(reg);
        if (!dynaMsg) {
            return content;
        }
        const { context, viewParams, data } = param;
        const env = App.getProjectSetting();
        dynaMsg.forEach((item: string) => {
            let msgPart = '';
            if (env.hasOwnProperty(item)) {
                msgPart = (env as any)[item];
            }
            if (context.hasOwnProperty(item)) {
                msgPart = context[item];
            }
            if (viewParams.hasOwnProperty(item)) {
                msgPart = viewParams[item];
            }
            if (data.hasOwnProperty(item)) {
                msgPart = data[item];
            }
            content = content.replace('${' + item + '}', msgPart);
        })
        // 解析动态文本内容
        return content;
    }


    /**
     *
     *
     * @param {string} name
     * @param {{ context: any, viewParams: any, data: any }} data
     * @param {('success' | 'info' | 'warning' | 'error')} type
     * @param {Function} callback
     * @memberof CtrlMsgContainer
     */
    alertMsg(name: string, data: { context: any, viewParams: any, data: any }, type: 'success' | 'info' | 'warning' | 'error', callback: Function) {
        const msg = this.CtrlMsgMap.get(name);
        if (msg) {
            let { timer } = msg;
            const message = this.formatMsgContent(msg, data);
            App.getNotificationHelper()[type](App.ts(`app.notificationtitle.${type}`), message, { duration: timer >= 0 ? (timer / 1000) : null });
        } else {
            callback();
        }
    }

}
